package com.storm.lib.template;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;

import com.storm.lib.type.SystemType;
import com.storm.lib.util.ExceptionUtil;
import com.storm.lib.util.FileUtil;
import com.storm.lib.util.PropertyUtil;
import com.storm.lib.util.XMLUtil;
@Controller
public class SystemTemplate {
	public static short SERVER_STATUS = SystemType.SERVER_STATUS_RUN;


	/**
	 * 命令映射表,key = orderNumber value =order的Class部
	 */
	public static ConcurrentHashMap<Integer, String> orderClassMapping = new ConcurrentHashMap<Integer, String>();

	/**
	 * 命令映射表,key = orderNumber value =order的Method部
	 */
	public static ConcurrentHashMap<Integer, String> orderMethodMapping = new ConcurrentHashMap<Integer, String>();
	
	public static String protocalPath;
	public static String constantPath;
	public static void init() {
		File propertiesFile = FileUtil.getUnderConfigFile("system.properties");
		Properties properties = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(propertiesFile);
			properties.load(fis);
		} catch (Exception e) {
			ExceptionUtil.throwInvalidParamException();
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				ExceptionUtil.processPrintException(e);
			}
		}
		protocalPath = null;
		constantPath = null;
		protocalPath = PropertyUtil.getValueIfNotNull(properties,"protocal_path", protocalPath);
		constantPath = PropertyUtil.getValueIfNotNull(properties,"constant_path", constantPath);
	}
	
	
	public static void loadProtocal() {
		File file = new File(protocalPath);
		Document doc = XMLUtil.getDom4JDocument(file);
		Element root = doc.getRootElement();
		List<Element> commands = root.elements("command");
		for (Element element : commands) {
			Integer orderNum = Integer.valueOf(element.attribute("id").getStringValue());
			String order1 = element.attribute("order1").getStringValue();
			String order2 = element.attribute("order2").getStringValue();
			orderClassMapping.put(orderNum, order1);
			orderMethodMapping.put(orderNum, order2);
		}
	}
	
	
	public static Integer fetchOrderId(String order) {
		String[] array = order.split("\\.");
		String className = array[0];
		String methodName = array[1];
		for(Integer orderId : orderClassMapping.keySet()){
			String orderClass = orderClassMapping.get(orderId);
			if(orderClass.equals(className)){
				String orderMethod = orderMethodMapping.get(orderId);
				if(orderMethod.equals(methodName)){
					return orderId;
				}
			}
		}
		ExceptionUtil.throwInvalidParamException("没找到指令"+order);
		return null;
	}
}
